/**
 * 这是操作echarts公用工具，目的为了抽取使用过程中频繁的重复操作和重复代码的复用
 */

var ECharts={
 
	//用于加载Echarts配置文件，container:为页面要渲染图表的容器，option为已经初始化好的图表类型的option配置
	ChartConfig:function(container,option){
		/*var chart_path = "static/libs/echarts/echarts"; //图表请求路径
		var theme_path="static/libs/echarts/shine";//主题请求路径
        //var map_path = "/resources/echarts/echarts-map";//地图的请求路径
 
        require.config({//引入常用的图表类型的配置
            paths: {
                'echarts': chart_path,
                'echarts/chart/bar': chart_path,//柱状图引入
                'echarts/chart/pie': chart_path,//饼状图引入
                'echarts/chart/line': chart_path,//折线图引入
                'echarts/chart/k': chart_path,//K线图引入,启用时取消注释
                'echarts/chart/scatter': chart_path,//散点图引入,启用时取消注释
                'echarts/chart/radar': chart_path,//雷达图引入,启用时取消注释
                'echarts/chart/chord': chart_path,//和弦图引入,启用时取消注释
                'echarts/chart/force': chart_path,//力导向布局图引入,启用时取消注释
                'theme': theme_path//主题
                //'echarts/chart/map': map_path//地图引入
            }
        });*/
        this.option = { chart: {}, option: option, container: container };
        return this.option;
	},
	//数据格式化
	ChartDataFormate:{
		//data的格式如 Result1=[{name:XXX,value:XXX},{name:XXX,value:XXX}….]，这种格式的数据，多用于饼图、单一的柱形图的数据源
		 FormateNOGroupData: function (data) { 
	            var categories = [];
	            var datas = [];
	            for (var i = 0; i < data.length; i++) {
	                categories.push(data[i].name || "");
	                datas.push({ name: data[i].name, value: data[i].value || 0 });
	            }
	            return { category: categories, data: datas };
	        },
	      //data的格式如 Result2=[{name:XXX,group:XXX,value:XXX},{name:XXX,group:XXX,value:XXX}]
	      //type为要渲染的图表类型：可以为line，bar，is_stack表示为是否是堆积图，展示多条折线图、分组的柱图
	        FormateGroupData: function (data, type, is_stack,is_min,is_max,is_avg,yAxisIndex) {
	            var chart_type = 'line';//默认设置为折线统计图
	            if (type){
	                chart_type = type;
	            }
	            var xAxis = [];//横坐标
	            var group = [];//分组类型
	            var series = [];//数据分组系列
	            for (var i = 0; i < data.length; i++) {
	            	if(xAxis.length<1){
	            		xAxis.push(data[i].name);
	            	}
	                for (var j = 0; j <i&&xAxis[j-1] != data[i].name; j++){
		                if (j == xAxis.length){
		                    xAxis.push(data[i].name);
		                }
	                }
	                if(group.length<1){
	                	group.push(data[i].group);
	                }
	                for (var k = 0; k < i&& group[k-1] != data[i].group; k++){
		                if (k == group.length){
		                    group.push(data[i].group);
		                }
	                }
	            }
	            for (var i = 0; i < group.length; i++) {
	                var temp = [];
	                var series_temp={};
	                for (var j = 0; j < data.length; j++) {
	                    if (group[i] == data[j].group) {
	                        if (type == "map"){
	                            temp.push({ name: data[j].name, value: data[i].value });
	                        }else if(type=="scatter"){
	                        	var temp_scatter=[];
	                        	temp_scatter.push(data[j].name);
	                        	temp_scatter.push(data[j].value);
	                            temp.push(temp_scatter);
	                        }else{
	                        	temp.push(data[j].value);
	                        }
	                    }
	                }
	                switch (type) {
	                    case 'bar'://柱状图
	                        series_temp = { name: group[i], data: temp, yAxisIndex:yAxisIndex, type: chart_type };
	                        if (is_stack){
	                            series_temp = $.extend({}, { stack: 'stack' }, series_temp);
	                        }
	                        if(is_min&&is_max){
	                        	series_temp = $.extend({},  {markPoint:{data: [{type: 'max', name: '最大值', symbolSize:18}, {type: 'min', name: '最小值'}]}}, series_temp);
	                        }else if(is_min){
	                        	series_temp = $.extend({},  {markPoint:{data: [{type: 'min', name: '最小值'}]}}, series_temp);
	                        }else if(is_max){
	                        	series_temp = $.extend({},  {markPoint:{data: [{type: 'max', name: '最大值', symbolSize:18}]}}, series_temp);
	                        }
	                        if(is_avg){
	                        	series_temp = $.extend({},  {markLine:{data:[{type:'average', name : '平均值'}]}}, series_temp);
	                        }
	                        break;
	                    case 'map'://地图（无堆积）
	                        series_temp = {
	                            name: group[i], type: chart_type, mapType: 'china', selectedMode: 'single',
	                            itemStyle: {
	                                normal: { label: { show: true} },
	                                emphasis: { label: { show: true} }
	                            },
	                            data: temp,
	                        };
	                        break;
	                    case 'line'://线状图
	                        series_temp = { name: group[i], data: temp, yAxisIndex:yAxisIndex, type: chart_type };
	                        if (is_stack){
	                            series_temp = $.extend({}, { stack: 'stack' }, series_temp);
	                        }
	                        if(is_min&&is_max){
	                        	series_temp = $.extend({},  {markPoint:{data: [{type: 'max', name: '最大值', symbolSize:18}, {type: 'min', name: '最小值'}]}}, series_temp);
	                        }else if(is_min){
	                        	series_temp = $.extend({},  {markPoint:{data: [{type: 'min', name: '最小值'}]}}, series_temp);
	                        }else if(is_max){
	                        	series_temp = $.extend({},  {markPoint:{data: [{type: 'max', name: '最大值', symbolSize:18}]}}, series_temp);
	                        }
	                        if(is_avg){
	                        	series_temp = $.extend({},  {markLine:{data:[{type:'average', name : '平均值'}]}}, series_temp);
	                        }
	                        break;//若需要更多图形往下添加
	                    case 'scatter'://散点图
	                    	series_temp = { name: group[i], data: temp, yAxisIndex:yAxisIndex, type: chart_type };
	                        if (is_stack){
	                            series_temp = $.extend({}, { stack: 'stack' }, series_temp);
	                        }
	                        if(is_min&&is_max){
	                        	series_temp = $.extend({},  {markPoint:{data: [{type: 'max', name: '最大值', symbolSize:18}, {type: 'min', name: '最小值'}]}}, series_temp);
	                        }else if(is_min){
	                        	series_temp = $.extend({},  {markPoint:{data: [{type: 'min', name: '最小值'}]}}, series_temp);
	                        }else if(is_max){
	                        	series_temp = $.extend({},  {markPoint:{data: [{type: 'max', name: '最大值', symbolSize:18}]}}, series_temp);
	                        }
	                        if(is_avg){
	                        	series_temp = $.extend({},  {markLine:{data:[{type:'average', name : '平均值'}]}}, series_temp);
	                        }
	                        break;//若需要更多图形往下添加
	                    default:
	                        series_temp = { name: group[i], data: temp, type: chart_type };
	                }
	                series.push(series_temp);
	            }
	            return { category: group, xAxis: xAxis, series: series };
	        }
	 },
	//初始化常用的图表类型
	ChartOptionTemplates:{
		//通用的图表基本配置
		CommonOption: {
            tooltip: {
                trigger: 'item'//tooltip触发方式:axis以X轴线触发,item以每一个数据项触发
            },
            toolbox: {
                show: false, //是否显示工具栏
                /*feature: {
                	 mark : {show: true},
                	 dataZoom : {show: true},
                     dataView : {show: true, readOnly: false},//数据预览
                     restore : {show: true},//复原
                     saveAsImage : {show: true}//是否保存图片
                }*/
            }
        },
      //通用的折线图表的基本配置
        CommonLineOption: {
            tooltip: {
                trigger: 'axis'
            },
            toolbox: {
                show: true,
                feature: {
                	 mark : {show: true},
                     dataView : {show: true, readOnly: false},//数据预览
                     magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},//支持柱形图和折线图的切换
                     restore : {show: true},//复原
                     saveAsImage : {show: true}//是否保存图片

                }
            }
        },
        //普通饼状图
        Pie: function (data, name,title,subTitle) {//data:数据格式：{name：xxx,value:xxx}...
            var pie_datas = ECharts.ChartDataFormate.FormateNOGroupData(data);//获取饼状图数据格式
            var option = {
            	title : {
            		 text: title,
            		 subtext: subTitle,//副标题
            		 x:'center'
            	},
                tooltip: {
                    trigger: 'item',
                    formatter:  "{a} <br/>{b} : {c} ({d}%)",
                    show: true
                },
                legend: {//标注
                    orient: 'vertical',
                    x: 'left',
                    data: pie_datas.category
                },
                calculable : true,//拖曳重算
                series: [
                    {
                        name: name || "",
                        type: 'pie',
                        radius: '65%',
                        center: ['50%', '50%'],
                        selectedMode: 'single',
                        data: pie_datas.data
                    }
                ]
            };
            return $.extend({}, ECharts.ChartOptionTemplates.CommonOption, option);
        },
        Lines: function (data, name, is_stack,is_min,is_max,is_avg,title,subTitle) { //data:数据格式：{name：xxx,group:xxx,value:xxx}...
            var stackline_datas = ECharts.ChartDataFormate.FormateGroupData(data, 'line', is_stack,is_min,is_max,is_avg,'0');
            var option = {
            	title : {
            		text: title,
            		subtext: subTitle
            		    },
                legend: {
                    data: stackline_datas.category
                },
                xAxis: [{
                    type: 'category', //X轴均为category，Y轴均为value
                    data: stackline_datas.xAxis,
                    boundaryGap: false//数值轴两端的空白策略
                }],
 
                yAxis: [{
                    name: name || '',
                    type: 'value',
                    splitArea: { show: true }
                }],
                series: stackline_datas.series
            };
            return $.extend({}, ECharts.ChartOptionTemplates.CommonLineOption, option);
        },
        Bars: function (data, name, is_stack,is_min,is_max,is_avg,title,subTitle) {//data:数据格式：{name：xxx,group:xxx,value:xxx}...
            var bars_dates = ECharts.ChartDataFormate.FormateGroupData(data, 'bar', is_stack,is_min,is_max,is_avg,'0');
           
            var option = {
            	title : {
            	    text: title,
            	    subtext: subTitle
            	},
                legend: {data:bars_dates.category},
                xAxis: [{
                    type: 'category',
                    data: bars_dates.xAxis,
                    axisLabel: {
                        show: true,
                        interval: 'auto',
                        rotate: 0,
                        margion: 8
                    }
                }],
                yAxis: [{
                    type: 'value',
                    name: name || '',
                    splitArea: { show: true }
                }],
                series: bars_dates.series
            };
            return $.extend({}, ECharts.ChartOptionTemplates.CommonLineOption, option);
        },
        //线柱混合图
        BarandLines: function (data0,data1, name0,name1, is_stack,is_min,is_max,is_avg,title,subTitle) {//data:数据格式：{name：xxx,group:xxx,value:xxx}...
            var bars_datas = ECharts.ChartDataFormate.FormateGroupData(data0, 'bar', is_stack,is_min,is_max,is_avg,'0');
            var line_datas = ECharts.ChartDataFormate.FormateGroupData(data1, 'line', is_stack,is_min,is_max,is_avg,'1');
            for(var i=0;i<bars_datas.category.length;i++){
            	var flag=1;
            	if(bars_datas.category[i]!=undefined){
            		for(var j=line_datas.category.length+i;j>=line_datas.category.length;j--){
            			if(line_datas.category[j-1]!=bars_datas.category[i]&&line_datas.category[j]!=bars_datas.category[i]){
            				flag=0;
            			}else{
            				flag=1;
            				break;
            			}
            			if(flag==0){
                			line_datas.category.push(bars_datas.category[i]);
                			line_datas.series.push(bars_datas.series[i]);
                		}
            		}

            	}
            	
            }
            
            var option = {
            	title : {
            	    text: title,
            	    subtext: subTitle
            	},
            	
                legend: {
                	data:line_datas.category,
                    y : 'bottom',
                    x:'left'
                	},
                xAxis: [{
                    type: 'category',
                    data: line_datas.xAxis,
                    axisLabel: {
                        show: true,
                        interval: 'auto',
                        rotate: 0,
                        margion: 8
                    }
                }],
                yAxis: [{
                    type : 'value',
                    name : name0||'',
                    axisLabel : {
                        formatter: '{value}万元'
                    },
                    splitArea : {show : true}},
                {
                    type : 'value',
                    name : name1||'',
                    axisLabel : {
                        formatter: '{value}%'
                    },
                    splitLine : {show : false}
                }],
                series: line_datas.series
            };
            return $.extend({}, ECharts.ChartOptionTemplates.CommonLineOption, option);
        },
      //内嵌饼状图
        NestPie: function (inData,outData, name,title,subTitle) {//data:数据格式：{name：xxx,value:xxx}...
            var pie_datas_in = ECharts.ChartDataFormate.FormateNOGroupData(inData);//获取饼状图数据格式
            var pie_datas_out = ECharts.ChartDataFormate.FormateNOGroupData(outData);//获取饼状图数据格式
            for(var i=0;i<inData.length;i++){
            	pie_datas_out.category.push(pie_datas_in.category[i]);
            }
            
            var option = {
            	title : {
            		 text: title,
            		 subtext: subTitle,//副标题
            		 x:'center'
            	},
                tooltip: {
                    trigger: 'item',
                    formatter:  "{a} <br/>{b} : {c} ({d}%)",
                    show: true
                },
                legend: {//标注
                    orient: 'vertical',
                    x: 'left',
                    data: pie_datas_out.category
                },
                calculable : true,//拖曳重算
                series: [
                    {
                        name: name || "",
                        type: 'pie',
                        radius: [0, 80],
                        selectedMode: 'single',
                        data: pie_datas_in.data,
                        itemStyle : {
                            normal : {
                                label : {
                                    position : 'inner'
                                },
                                labelLine : {
                                    show : false
                                }
                            }
                        }
                    },
                    {
                        name:name || "",
                        type:'pie',
                        radius : [100, 150],
                        data:pie_datas_out.data
                    }
                ]
            };
            return $.extend({}, ECharts.ChartOptionTemplates.CommonOption, option);
        },
        //散点图加入
        Scatter:function(data, name, is_stack,is_min,is_max,is_avg,title,subTitle){//data:数据格式：{name：xxx,group:xxx,value:xxx}...
            var scatter_datas = ECharts.ChartDataFormate.FormateGroupData(data, 'scatter', is_stack,is_min,is_max,is_avg,'0');
            var option = {
            	    title : {
            	        text: title,
            	        subtext: subTitle
            	    },
            	    tooltip : {
            	    	showDelay : 0,
            	        axisPointer:{
            	            type : 'cross',
            	            lineStyle: {
            	            	color: '#1e90ff',
            	                type : 'dashed',
            	                width : 1
            	            }
            	        },
            	    formatter:  function (value) {
                        if (value[2].length > 1) {
                            return value[0] + ' :<br/>'
                               + value[2][0] + 'cm ' 
                               + value[2][1] + 'kg ';
                        }
                        else {
                            return value[0] + ' :<br/>'
                               + value[1] + ' : '
                               + value[2] + 'kg ';
                        }
                    }
            	    },
            	    legend: {
            	        data:scatter_datas.category
            	    },
            	   
            	    xAxis : [
            	        {
            	            type : 'value',
            	            power: 1,
            	            precision: 2,
            	            scale:true,
            	            axisLabel : {
            	                formatter: '{value} cm'
            	            }
            	        }
            	    ],
            	    yAxis : [
            	        {
            	            type : 'value',
            	            power: 1,
            	            precision: 2,
            	            scale:true,
            	            axisLabel : {
            	                formatter: '{value} kg'
            	            }
            	        }
            	    ],
            	    series : scatter_datas.series
            	};
            	                
            return option;
        	
        },
        //地图统计加入
       Map:function (data, name, title,subTitle) {//data:数据格式：{name：xxx,group:xxx,value:xxx}...
           var map_datas = ECharts.ChartDataFormate.FormateGroupData(data, 'map', false,false,false,false,'0');
           option = {
        		    title : {
        		        text: title,
        		        subtext: subTitle,
        		        x:'center'
        		    },
        		    tooltip : {
        		        trigger: 'item',
        		        
                        show: true
        		    },
        		    legend: {
        		        orient: 'vertical',
        		        x:'left',
        		        data:map_datas.category
        		    },
        		    dataRange: {
        		        min: 0,
        		        max: 2500,
        		        x: 'left',
        		        y: 'bottom',
        		        text:['高','低'],           // 文本，默认为数值文本
        		        calculable : true
        		    },
        		    toolbox: {
        		        show : true,
        		        orient : 'vertical',
        		        x: 'right',
        		        y: 'center',
        		        feature : {
        		            mark : {show: true},
        		            dataView : {show: true, readOnly: false},
        		            restore : {show: true},
        		            saveAsImage : {show: true}
        		        }
        		    },
        		    series :map_datas.series 
        		};
           return $.extend({}, ECharts.ChartOptionTemplates.CommonOption, option);
       }
        //若需其他图表在此增加
	},
	Charts:{ 
		//渲染图表
		 RenderChart: function (option) {
	            /*require([
	                'echarts',
	                'echarts/chart/line',
	                'echarts/chart/bar',
	                'echarts/chart/pie',
	                'echarts/chart/k',
	                'echarts/chart/scatter',
	                'echarts/chart/radar',
	                'echarts/chart/chord',
	                'echarts/chart/force',
	                'theme'
	                //'echarts/chart/map'
	              ],
	              function (ec,line,bar,k,scatter,radar,chord,force,theme) {
	                  echarts = ec;
	                  if (option.chart && option.chart.dispose){
	                      option.chart.dispose();
	                  }
	                  option.chart = echarts.init(option.container,theme);
	                  window.onresize = option.chart.resize;
	                  option.chart.setOption(option.option, true);
	 
	              });*/
			 if (option.chart && option.chart.dispose){
                 option.chart.dispose();
             }
	         option.chart = echarts.init(option.container,"shine");
             window.onresize = option.chart.resize;
             option.chart.setOption(option.option, true);
		 },
		//渲染地图
		RenderMap:function(option){

		}
	}
};
 
